package com.edu.edu.week_project01.activity.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.edu.edu.week_project01.R;
import com.edu.edu.week_project01.activity.adapter.LbPageAdapter;

import java.util.ArrayList;
import java.util.List;

public class LbActivity extends AppCompatActivity {

    private ViewPager mVp;
    private TextView tvTitle;
    private LinearLayout llPoints;
    private List<ImageView> images;

    //处理消息
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                int index = msg.arg1;
                mVp.setCurrentItem(index);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lb);
        //初始化控件
        initView();
        //监听事件
        initListener();
    }

    private void initListener() {
        int[] imagesId = getImages();
        final String[] titles = getTitles();

        images = new ArrayList<>();
        for (int i = 0; i < imagesId.length; i++) {
            ImageView img = new ImageView(this);
            img.setBackgroundResource(imagesId[i]);
            images.add(img);

            //添加小圆点
            View point = new View(this);
            //获取屏幕信息的类
            DisplayMetrics metrics = new DisplayMetrics();
            //指定数值的单位
            float width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 15, metrics);
            float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 15, metrics);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) width, (int) height);
            //设置左边距
            params.leftMargin = 5;
            point.setLayoutParams(params);
            point.setBackgroundResource(R.drawable.normal_points);
            assert llPoints != null;
            llPoints.addView(point);
        }


        //设置标题和小圆点的默认值
        assert tvTitle != null;
        tvTitle.setText(titles[0]);
        assert llPoints != null;
        llPoints.getChildAt(0).setBackgroundResource(R.drawable.checked_points);

        assert mVp != null;
        mVp.setAdapter(new LbPageAdapter(images));

        //解决初始情况下,不能往左滑动的小bug.
        mVp.setCurrentItem(10000);
        mVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            //页面选择的方法.滚动完毕后...
            @Override
            public void onPageSelected(int position) {
                //改变标题
                tvTitle.setText(titles[position % images.size()]);
                tvTitle.setTextSize(10);
                tvTitle.setTextColor(Color.WHITE);

                for (int i = 0; i < llPoints.getChildCount(); i++) {
                    llPoints.getChildAt(i).setBackgroundResource(R.drawable.normal_points);
                    if (i == position % images.size()) {
                        llPoints.getChildAt(position % images.size()).setBackgroundResource(R.drawable.checked_points);
                    }
                }

            }
        });
        //开启线程
        final AutoRunThread mTask = new AutoRunThread();
        mTask.startRun();

        //处理ViewPager的触摸事件
        mVp.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN://按下事件,停止自动轮播
                        mTask.stopRun();
                        break;
                    case MotionEvent.ACTION_CANCEL://取消和抬起事件,开始自动轮播
                    case MotionEvent.ACTION_UP:
                        mTask.startRun();
                        break;
                }
                return false;
            }
        });
    }

    private void initView() {
        mVp = (ViewPager) findViewById(R.id.Lb_vp);
        tvTitle = (TextView) findViewById(R.id.Lb_tv_title);
        llPoints = (LinearLayout) findViewById(R.id.Lb_ll_points);
    }

    public int[] getImages() {

        return new int[]{ R.mipmap.image11, R.mipmap.image12, R.mipmap.image13, R.mipmap.image14};
    }

    public String[] getTitles() {
        return new String[]{ "朴树又回来了", "东风吹来一地鸡毛", "乐视TV送电视了", "如何做好一个屌丝?"};
    }
    //实现广告轮播的自动切换效果
    class AutoRunThread implements Runnable {

        private long delayTime = 2000;
        //任务是否开始
        private boolean isStart = false;

        //开始任务
        public void startRun() {
            if (!isStart) {
                //清除本次任务之前的所有其他任务
                mHandler.removeCallbacks(this);
                isStart = true;
                mHandler.postDelayed(this, delayTime);
            }
        }

        //停止任务
        public void stopRun() {
            if (isStart) {
                isStart = false;
                mHandler.removeCallbacks(this);
            }
        }

        @Override
        public void run() {

            //获取当前页面的索引值
            int currentItem = mVp.getCurrentItem();
            Message msg = Message.obtain();
            msg.what = 1;
            msg.arg1 = ++currentItem;
            mHandler.sendMessage(msg);

            //mHandler.sendMessageDelayed();
            //递归...
            mHandler.postDelayed(this, delayTime);
        }
    }
}
